package com.chimm.redpacket.demo_single;

import com.chimm.redpacket.bean.RedPacket;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Random;

/**
 * 抢红包设计方式一
 *
 * @author Chimm Huang
 */
public class Demo01 {

    public static void main(String[] args) {
        // 让开，我要发红包啦
        RedPacket redPacket = new RedPacket(BigDecimal.valueOf(100L), 5);
        System.err.printf("================ 红包来啦，金额：%s 元，数量：%s 个 ================%n", redPacket.getAmount(), redPacket.getNum());

        List<String> userList = List.of("刘一", "陈二", "张三", "李四", "王五");
        userList.parallelStream().forEach(user -> {
            BigDecimal money = getRandomMoney(redPacket);
            System.out.printf("================ %s 抢到了：%s 元 ================%n", user, money);
        });
    }

    /**
     * 获取红包金额
     */
    public static synchronized BigDecimal getRandomMoney(RedPacket redPacket) {
        // 剩余的红包数量
        Integer remainingNum = redPacket.getRemainNum();
        // 剩余的金额
        BigDecimal remainingAmount = redPacket.getRemainAmount();
        if (remainingNum == 1) {
            redPacket.setRemainNum(--remainingNum);
            redPacket.setRemainAmount(BigDecimal.ZERO);
            // 返回剩余金额
            return remainingAmount;
        }
        Random r = new Random();
        //最小金额
        BigDecimal min = BigDecimal.valueOf(0.01);
        //最大金额（开区间）
        BigDecimal max = remainingAmount.divide(new BigDecimal(remainingNum), 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(2L));

        //获取随机金额,不超过最大值max
        BigDecimal money = BigDecimal.valueOf(r.nextDouble()).multiply(max);
        // 如果随机金额=0，则取最小的值
        money = money.compareTo(min) <= 0 ? min : money;
        //向下取整后取小数点后2位
        money = money.setScale(2, RoundingMode.DOWN);

        //设置剩余金额
        remainingAmount = remainingAmount.subtract(money);
        redPacket.setRemainAmount(remainingAmount);
        //设置剩余红包个数
        redPacket.setRemainNum(--remainingNum);
        return money;
    }
}
